<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\DB;
class Appointment extends Model
{
    
    protected $table = "c_appointments";

    public function addAppointment($data)
    {
        try {
            DB::beginTransaction(); // 开始事务
            if (isset($data['id']) && !empty($data['id'])) { // 更新
                $redata = $this->getInfo($data['id']);
                if($redata->pay_status ==1){
                    return "您已经支付该订单,不能修改";
                }
                $redata->user_id = isset($data['user_id']) ? $data['user_id'] : $redata->user_id;
                $redata->phone = isset($data['phone']) ? $data['phone'] : $redata->phone;
                $redata->type = isset($data['type']) ? $data['type'] : $redata->type;
                $redata->doc_id = isset($data['doc_id']) ? $data['doc_id'] : $redata->doc_id;
                $redata->rever_date = isset($data['rever_date']) ? $data['rever_date'] : $redata->dates;
                $redata->rever_time = isset($data['rever_time']) ? $data['rever_time'] : $redata->rever_time;
                $redata->remark = isset($data['remark']) ? $data['remark'] : $redata->remark;
                $redata->price = isset($data['price']) ? $data['price'] : $redata->price;
                $redata->pay_type = isset($data['pay_type']) ? $data['pay_type'] : $redata->pay_type;
                $res = $redata->save();
            } else {
                //添加
                $this->user_id = isset($data['user_id']) ? $data['user_id'] : 0;
                $this->phone = isset($data['phone']) ? $data['phone'] : "";
                $this->type = isset($data['type']) ? $data['type'] : 0;
                $this->doc_id = isset($data['doc_id']) ? $data['doc_id'] : 0;
                $this->rever_date = isset($data['rever_date']) ? $data['rever_date'] : "";
                $this->rever_time = isset($data['rever_time']) ? $data['rever_time'] : "";
                $this->remark = isset($data['remark']) ? $data['remark'] : "";
                $this->price = isset($data['price']) ? $data['price'] : 0;
                $this->pay_type = isset($data['pay_type']) ? $data['pay_type'] : 0;
                $res = $this->save();
            }
            if ($res) {
                DB::commit(); // 提交事务
                return ['appointment_id' => $this->id ?: $data['id']];
            } else {
                return '预约失败';
                DB::rollback(); // 回滚事务
            }
        } catch (Exception $e) {
            DB::rollback(); // 回滚事务
        }
    }

    /**
     * @param $id
     * @return mixed
     * 查询信息
     */
    public function getInfo($id)
    {
        return $this->where([['id','=',$id]])->first();
    }
}
